package com.wlyuan.gateway.exception;

import com.wlyuan.gateway.utils.ResponseUtils;
import com.wlyuan.utils.ResultError;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.lang.NonNull;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author yuanzheng
 */
@Slf4j
@Component
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, @NonNull Throwable e) {
        var response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(e);
        }

        if (e instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) e).getStatus());
        }
        logger.error("Handler error: {}", exchange.getRequest().getPath(), e);
        String requestPath = exchange.getRequest().getURI().getPath();
        ResultError error;
        if (e instanceof InvalidTokenException) {
            error = new ResultDecorator(AuthorizationError.TOKEN_INVALID, requestPath);
        } else {
            error = new ResultDecorator(AuthorizationError.UNAUTHORIZED, requestPath);
        }
        return ResponseUtils.writeWith(response, error);
    }
}
